package com.lizonghui.googleplay.protocol;

import com.google.gson.Gson;
import com.lizonghui.googleplay.bean.HomeInfoBean;
import com.lizonghui.googleplay.config.Constants;
import com.lizonghui.googleplay.utils.HttpUtils;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2016/6/21.
 * 负责homeFragment的okHttp请求
 * 抽取homeFragment的网络请求,是的Fragment的结构不那么臃肿
 */
public class HomeProtocolBackUp {
    /**
     * @param index 分页请求的索引
     * @return
     * @throws IOException
     */
    public HomeInfoBean loadData(int index) throws IOException {
        //使用okHttp请求网络数据
        //创建okHttpClient实例对象
        OkHttpClient okHttpClient = new OkHttpClient();

        String url = Constants.URLS.BASEURL + "home";
        //参数
        Map<String, Object> parmasMap = new HashMap<>();
        parmasMap.put("index", "" + index);
        String urlParamsByMap = HttpUtils.getUrlParamsByMap(parmasMap);
        //dir=E:\\GooglePlay\\googlePlay_day01\\资料\\服务器
        //http://localhost:8080/GooglePlayServer/home?index=0这里不能是localhost，要是具体IP
        //http://192.168.0.83:8080/GooglePlayServer/home?index=1
        //拼接之后的结果
        url = url + urlParamsByMap;

        //创建一个请求对象
        Request request = new Request.Builder().get().url(url).build();

        //发起同步请求,因为这里已经是子线程，所以用同步请求
        Response response = okHttpClient.newCall(request).execute();

        if (response.isSuccessful()) {//响应成功
            String resultJsonString = response.body().string();

            //解析用Gson
            Gson gson = new Gson();
            HomeInfoBean homeInfoBean = gson.fromJson(resultJsonString, HomeInfoBean.class);
            //每次返回都要判断返回的JSON值，这里我们定义方法在BaseFragment
            return homeInfoBean;
        } else {
            return null;
        }
    }
}
